
package com.borqs.music.ui;

import com.borqs.music.R;
import com.borqs.music.util.MusicConf;
import com.borqs.music.util.MyLogger;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class DevConfigActivity extends Activity implements OnClickListener, OnCheckedChangeListener {
    static MyLogger logger = MyLogger.getLogger("DevConfigActivity");
    private static final String CONFIG_FILE = "/data/data/com.borqs.music/music.json";

    // JSON name field.
    private static final String JSON_SERVER = "server";
    private static final String JSON_VERSION = "version";

    // XXX should update the version when changed the value
    // TEST_SERVER or BUSINESS_SERVER blow
    private static final int CONFIG_VERSION = 2;

    private static String TEST_SERVER = "http://apptest0.borqs.com/music/";
    private static String DEV_SERVER = "http://122.200.74.233/";

    private EditText etServerUrl;
    private RadioGroup rgServer;

    private JSONObject configObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dev_config);
        configObject = getConfig();
        String lastServer = configObject.optString(JSON_SERVER, TEST_SERVER);
        int checkedId = -1;
        if (DEV_SERVER.equals(lastServer)) {
            checkedId = R.id.radio_dev;
        } else if (TEST_SERVER.equals(lastServer)) {
            checkedId = R.id.radio_test;
        } else {
            checkedId = R.id.radio_custom;
        }

        etServerUrl = (EditText) findViewById(R.id.server_url);

        if (checkedId == R.id.radio_custom) {
            etServerUrl.setEnabled(true);
            etServerUrl.setText(lastServer);
        } else {
            etServerUrl.setEnabled(false);
            etServerUrl.setText(TEST_SERVER);
        }

        rgServer = (RadioGroup) findViewById(R.id.server);
        rgServer.check(checkedId);
        rgServer.setOnCheckedChangeListener(this);

        Button btnOk = (Button) findViewById(R.id.confirm);
        btnOk.setOnClickListener(this);

        Button btnCancel = (Button) findViewById(R.id.cancel);
        btnCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.confirm) {
            int checkId = rgServer.getCheckedRadioButtonId();
            try {
                switch (checkId) {
                    case R.id.radio_dev:
                        configObject.put(JSON_SERVER, DEV_SERVER);
                        saveConfig(configObject);
                        break;
                    case R.id.radio_test:
                        configObject.put(JSON_SERVER, TEST_SERVER);
                        saveConfig(configObject);
                        break;
                    case R.id.radio_custom:
                        String serverUrl = etServerUrl.getText().toString();
                        URL url = new URL(serverUrl); // check the URL
                        configObject.put(JSON_SERVER, url.toString());
                        saveConfig(configObject);
                        break;
                }
                finish();
            } catch (JSONException jex) {
                jex.printStackTrace();
            } catch (MalformedURLException mex) {
                Toast.makeText(this, R.string.dev_config_server_error, Toast.LENGTH_SHORT).show();
                mex.printStackTrace();
            }
        } else if (id == R.id.cancel) {
            finish();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        etServerUrl.setEnabled(checkedId == R.id.radio_custom);
    }

    private static JSONObject getConfig() {
        File file = new File(CONFIG_FILE);
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = fis.read(buffer)) > -1) {
                    bos.write(buffer, 0, len);
                }
                fis.close();
                bos.close();

                JSONObject jobj = new JSONObject(bos.toString());
                int version = jobj.optInt(JSON_VERSION, 0);
                if (version != CONFIG_VERSION) {
                    logger.d("version mismatch, need = " + CONFIG_VERSION + ", but = " + version);
                    file.delete();
                } else {
                    return jobj;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException jsonEx) {
                jsonEx.printStackTrace();
                // IllegalStateException, file not JSON format.
            }
        }

        return new JSONObject();
    }

    private static void saveConfig(JSONObject config) {
        if (config == null) {
            logger.d("save config failed, shouldn't be null.");
            return;
        }

        File file = new File(CONFIG_FILE);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }

            if (config.has(JSON_VERSION)) {
                config.put(JSON_VERSION, CONFIG_VERSION);
            }

            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = config.toString(2).getBytes();
            fos.write(buffer);
            fos.close();
        } catch (JSONException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String server = config.optString(JSON_SERVER, DEV_SERVER);
        MusicConf.setServerUrl(server);
    }

    public static String getServerUrl() {
        JSONObject jobj = getConfig();
        String server = jobj.optString(JSON_SERVER, DEV_SERVER);
        return server;
    }
}
